package com.gm.commonlib.filters;

import android.text.InputFilter;
import android.text.Spanned;

import java.util.regex.Pattern;

public class RegexInputFilter implements InputFilter {

    Pattern enterPattern = null;
    boolean mExpectMatch = true;

    /**
     * @param regex 内容正则表达式
     * @param expectMatch  true 期望匹配, false 期望不匹配
     * 如果内容和正则表达式匹配，如果是想匹配留下的内容，则显示到输入框，否则不显示到输入框
     * 如果内容和正则表达式不匹配，正好与上面相反
     */
    public RegexInputFilter(String regex, boolean expectMatch) {
        enterPattern = Pattern.compile(regex);
        this.mExpectMatch = expectMatch;
    }

    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        if(enterPattern != null) {
            if (enterPattern.matcher(source).matches()) {
                if (mExpectMatch) {
                    return source;
                } else {
                    return "";
                }
            } else {
                if (mExpectMatch) {
                    return "";
                } else {
                    return source;
                }
            }
        } else {
            return source;
        }
    }
}
